package remote;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.remoting.rmi.RmiProxyFactoryBean;

import com.zsgl.util.ClassUtil;

public class RemoteService implements ApplicationContextAware {
	
	AbstractApplicationContext context;
	
	Map<String, String> exportPackages;
	
	public RemoteService(Map<String, String> exportPackages) {
		this.exportPackages = exportPackages;
	}
	
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		this.context = (AbstractApplicationContext)context;
	}
	
	public void initRemoteInterface() throws Exception {
		List<Class<?>> classes = new ArrayList<Class<?>>();
		for (String str : exportPackages.keySet()) {
			classes.addAll(ClassUtil.getAllInterface(str));
		}
		for (Class<?> clazz : classes) {
			ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
			RmiProxyFactoryBean bean = RmiProxyFactoryBean.class.newInstance();
			String url = makeUrl(clazz);
			bean.setServiceUrl(url);
			bean.setServiceInterface(clazz);
			bean.afterPropertiesSet();
			beanFactory.registerSingleton(clazz.getSimpleName(), bean);
			System.out.println("Init Remote Interface : " + url);
		}
	}
	
	public String makeUrl(Class<?> clazz) {
		return makeUrl(exportPackages.get(clazz.getPackage().getName()), clazz);
	}
	
	public static String makeUrl(String host, Class<?> clazz) {
		return "rmi://" + host + ":8888/" + clazz.getSimpleName();
	}
	
}
